<!--
登录页
郭萍
2017-3-30
-->
<template>
  <el-row type="flex"  justify="center" style="background-color:#fff">
    <el-col :span="24">
      <el-col :span="3" style="margin:6px 0">
      </el-col>
      <el-col :span="6" style="margin:8px 0;font-size: 20px;line-height: 45px;font-weight: 600;">
        <!--<img src="../common/img/logo-top.png"  style="vertical-align:bottom" title="花都照明管理处路灯信息采集系统"/>-->
        路灯宝信息一体化管理平台
      </el-col>
      <el-col :span="10" style="margin:6px 0">
      </el-col>
      <!--<el-col :span="5" style="margin-top:20px">
        <span class="linkcolor" @click="linkTo('eb')">供应商链接</span><span style="margin:0 5px;">|</span><span class="linkcolor" @click="linkTo('md')">门店链接</span>
      </el-col>-->
      <el-col :span="24" class="bg-container">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-position="left" label-width="0px" class="demo-ruleForm login-container">
          <h3 class="title">系统登录</h3>
          <el-form-item prop="account">
            <el-input type="text" v-model="ruleForm.account" auto-complete="off" placeholder="账号" @keyup.enter.native.prevent="defaultLogin"></el-input>
          </el-form-item>
          <el-form-item prop="checkPass">
            <el-input type="password" v-model="ruleForm.checkPass" auto-complete="off" placeholder="密码" @keyup.enter.native.prevent="defaultLogin"></el-input>
          </el-form-item>
          <el-form-item prop="kaptcha" v-show="kaptchaStyle">
            <el-input type="text" v-model="ruleForm.kaptcha" placeholder="验证码" auto-complete="off" style="width:140px;"></el-input>
            <template>
              <img :src="srcUrl" style="width: 90px;height: 35px;vertical-align:top" alt="看不清？点击换一个" title="看不清？点击换一个" @click="reloadFun"/>
            </template>
          </el-form-item>
          <!--<el-form-item v-show="luosiStyle">-->
            <!--<div class="l-captcha" data-site-key="65e2b72fd43df7bee09d797dada748f6"></div>-->
          <!--</el-form-item>-->
          <el-form-item style="width:100%;margin-top:40px">
            <el-button  style="width:100%" :loading="logining" id="loginbtn" @click="defaultLogin">登录</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <!--<el-col :span="24">-->
        <!--<div style="text-align:center;margin:20px 0;color:#646464;font-size:13px;">为了您更好的使用系统，建议使用Chrome浏览器。 <a class="linkcolor" href="http://sw.bos.baidu.com/sw-search-sp/software/14aca1f5063ab/ChromeStandalone_59.0.3071.115_Setup.exe" style="text-decoration:none">点击下载Chrome</a></div>-->
      <!--</el-col>-->
      <!-- <el-col :span="24" style="margin:50px 0">
         <el-col :span="8" align="right"><img src="../common/img/hz01.png" style="width:180px"></el-col>
         <el-col :span="8" align="center"><img src="../common/img/hz02.png" style="width:180px"></el-col>
         <el-col :span="8" align="left"><img src="../common/img/hz03.png" style="width:180px"></el-col>
       </el-col>-->
      <el-col :span="24" style="text-align:center;">
        <!--<div style="text-align:center;margin:20px 0;color:#646464;font-size:13px">Copyright © 2017 北京途游国际旅行社有限公司  苏ICP备17023349号</div>-->
        <div style="text-align:center;margin:20px 0;color:#646464;font-size:13px">Copyright © 2020 无锡星语物联技术有限公司</div>
        <a href="https://beian.miit.gov.cn" target="_blank" style="color: #00a0e9;cursor: pointer">苏ICP备18008895号-3</a>
      </el-col>
    </el-col>
    <!-- 存放人机验证码response值，后台验证是否正确 -->
    <input type="hidden" id="lc-captcha-response" name="luotest_response" value="">
  </el-row>
</template>

<script type="text/ecmascript-6">
  import $ from 'jquery'
  import {initLSM, sortByMenuTop, sessionOut} from '../common/js/util.js' // 加载luosimao验证码方法
  export default {
    data () {
      // 登录账号过滤特殊字符串
      var validateAccount = (rule, value, callback) => {
        var teg = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
        if (teg.test(value) || value.trim() === '') {
          callback(new Error('请输入正确的账号'))
        } else {
          callback()
        }
      }
      // 验证字符验证码文本框信息
      var checkKaptcha = (rule, value, callback) => {
        if (this.kaptchaType === '2') {
          if (value === '') {
            callback(new Error('请输入验证码'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      return {
        logining: false,
        kaptchaStyle: false,
        luosiStyle: true,
        kaptchaType: '0', // 初始化为1 时  默认点选验证码
        menuList: [],
        srcUrl: '',
        ruleForm: {
          account: '',
          checkPass: '',
          kaptcha: ''
        },
        // 校验规则
        rules: {
          account: [
            { required: true, message: '请输入账号', trigger: 'blur' },
            { validator: validateAccount }
          ],
          checkPass: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ],
          kaptcha: [
            {required: true, validator: checkKaptcha, trigger: 'blur'}
          ]
        },
        checked: true
      }
    },
    methods: {
      linkTo (type) {
        if (type === 'eb') {
          window.location.href = 'http://tyeb.laidanyun.com/login'
        } else if (type === 'md') {
          window.location.href = 'http://tymd.laidanyun.com/login'
        }
      },
      // 读取缓存获取验证码的类型  ---验证码默认点选，暂时不用配置文件获取
      getTypeForKaptcha () {
        this.$http.post('/smartLight/web/baseConfig/getSysBaseConfigValue.htm').then(response => {
          var data = response.body
          if (data.isSuccess === 0) {
            this.kaptchaType = data.result
            if (this.kaptchaType === '0') {
            } else if (this.kaptchaType === '1') { // 点选验证码
              this.luosiStyle = true
            } else if (this.kaptchaType === '2') { // 字符验证吗
              this.kaptchaStyle = true
              this.srcUrl = '/smartLight/web/kaptcha/Kaptcha2.htm'
            } else if (this.kaptchaType === '3') { // 滑动验证码
              this.loadingGeetestCode() // 验证码初始化加载
            }
            if (this.kaptchaType !== '3') {
              let _this = this
              $('#loginbtn').click(function () {
                _this.handleSubmit()
              })
            }
          } else {
            this.$message({
              showClose: true,
              message: data.msg,
              type: 'error'
            })
          }
        })
      },
      // 点选默认登录页面
      defaultLogin () {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            // 获取验证码的值，后台二次验证是否通过
            var cap = $('#lc-captcha-response').val()
//            if (cap === '') {
//              this.$message({
//                showClose: true,
//                message: '请进行人机识别校验！',
//                type: 'error'
//              })
//              return false
//            }
            var loginParams = {
              loginName: this.ruleForm.account,
              password: this.ruleForm.checkPass,
              kaptchaType: this.kaptchaType,
              resp: cap,
              type: 0
            }
            this.checkResult(loginParams)
          } else {
            return false
          }
        })
      },
      // 点击图片重新刷新验证码信息
      reloadFun () {
        this.srcUrl = '/smartLight/web/kaptcha/Kaptcha2.htm?' + new Date().getTime()
      },
      // 初始化加载验证码
      loadingGeetestCode () {
        this.$http.get('/smartLight/web/kaptcha/startCaptcha.htm?t=' + (new Date()).getTime()).then(response => {
          var data = response.body
          data = JSON.parse(data)
          window.initGeetest({
            // 以下配置参数来自服务端 SDK
            gt: data.gt,
            challenge: data.challenge,
            offline: !data.success, // 表示用户后台检测极验服务器是否宕机
            new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机
            product: 'bind', // 产品形式，包括：float，popup
            width: '300px'
          }, this.bindGeetest)
        })
      },
      // 验证码的触发方法
      bindGeetest (captchaObj) {
        let _this = this
        $('#loginbtn').click(function () {
          _this.$refs.ruleForm.validate((valid) => {
            if (valid) {
              captchaObj.verify() // 登录信息验证通过显示验证码
            }
          })
        })
        // 滑动验证码验证成功后执行
        captchaObj.onSuccess(function () {
          var validate = captchaObj.getValidate()
          var loginParams = {
            loginName: _this.ruleForm.account,
            password: _this.ruleForm.checkPass,
            geetest_challenge: validate.geetest_challenge,
            geetest_validate: validate.geetest_validate,
            geetest_seccode: validate.geetest_seccode,
            kaptchaType: _this.kaptchaType,
            type: 0
          }
          setTimeout(function () {
            _this.checkResult(loginParams)
          }, 1000)
        })
      },
      // 登录方法，登录信息判断
      handleSubmit (ev) {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            var loginParams = {
              loginName: this.ruleForm.account,
              password: this.ruleForm.checkPass,
              kaptchaType: this.kaptchaType,
              type: 0
            }
            if (this.kaptchaType === '2') {
              loginParams = {
                loginName: this.ruleForm.account,
                password: this.ruleForm.checkPass,
                kaptcha: this.ruleForm.kaptcha,
                kaptchaType: this.kaptchaType,
                type: 0
              }
            } else if (this.kaptchaType === '1') {
              // 获取验证码的值，后台二次验证是否通过
              var cap = $('#lc-captcha-response').val()
              if (cap === '') {
                this.$message({
                  showClose: true,
                  message: '请进行人机识别校验！',
                  type: 'error'
                })
                return false
              }
              loginParams = {
                loginName: this.ruleForm.account,
                password: this.ruleForm.checkPass,
                kaptchaType: this.kaptchaType,
//                resp: cap,
                type: 0,
                channel: 0
              }
            }
            this.checkResult(loginParams)
          } else {
            return false
          }
        })
      },
      checkResult (params) {
        var that = this
        this.logining = true
        this.$http.post('/smartLight/web/baseAccount/login.htm', params).then(response => {
          var resBody = response.body
          this.logining = false
          var user = resBody.result
          if (resBody.isSuccess === 0) {
            console.log(user)
            // 登陆成功把用户信息存入缓存，跳转到渠道列表页面
            sessionStorage.setItem('prefix', user.secretQuestion) // 运营环境变量 t=测试环境
            sessionStorage.setItem('env', user.secretAnswer) // 运营环境变量 t=测试环境
            sessionStorage.setItem('user', JSON.stringify(user))
            sessionStorage.setItem('buttonIds', resBody.errorMsg) // 权限按钮ID集合
            sessionStorage.setItem('treamId', user.treamId)
            sessionStorage.setItem('userId', user.id)
            //  location.href = 'index.html'
            //  this.$router.push({ path: '/baseConfig' })
            //  this.$router.replace({ paueth: '/baseConfig' })
            //  window.location.href = '/adminAccountblk'
            //  that.$router.push({ path: '/survey' })

            this.$http.post('/smartLight/web/sysRole/getById.htm', {
              type: user.type,
              roleId: user.roleId
            }).then(response => {
              console.log('-----------------------')
              console.log(response.body)
              var resBody = response.body
              var isSuccess = resBody.isSuccess
              if (isSuccess === 0) { // 成功
                this.role = resBody.result
                this.menuList = JSON.parse(resBody.result.menu)
                console.log(this.menuList)
                // 过滤无效的一级菜单
                for (let i = 0; i < this.menuList.length; i++) {
                  if (!this.menuList[i].childNode) {
                    this.menuList.splice(i, 1)
                  }
                }
                sortByMenuTop(this.menuList)
                var way = this.menuList[0].childNode[0].childNode ? this.menuList[0].childNode[0].childNode[0].menuUrl : this.menuList[0].childNode[0].menuUrl
                that.$router.push({ path: way })
              } else if (isSuccess === 2) { // 超时
                sessionOut(this)
              } else { // 失败
                this.$message({
                  showClose: true,
                  message: resBody.errorMsg,
                  type: 'error'
                })
              }
            })
          } else if (resBody.isSuccess === -1) { // 结果为-1，验证码加载超时，需重新加载
            this.$alert(resBody.errorMsg, ' ', {
              type: 'warning'
            }).then(() => {
              sessionStorage.clear()
              this.$router.push({path: '/login'})
            })
          } else {
            if (this.kaptchaType === '2') {
              this.ruleForm.kaptcha = ''
              this.reloadFun()
            } else if (this.kaptchaType === '1') {
              window.LUOCAPTCHA.reset()
            }
            this.$message({
              showClose: true,
              message: resBody.errorMsg,
              type: 'error'
            })
          }
        })
      }
    },
    created () {
      initLSM($) // 动态加载luosimao验证码
      setTimeout(function () {
        if (window.LUOCAPTCHA) {
          window.LUOCAPTCHA.reset()
        }
      }, 300)
    },
    mounted () {
      // this.getTypeForKaptcha() // 初始化度取缓存获取登录的验证方式
      document.onkeydown = function (event) {
        if (event.keyCode === 13 || event.keyCode === '13') { // enter 键
          $('#loginbtn').trigger('click')
        }
      }
    } // ,
//    components: {
//      luosimao
//    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  body
    background-color:#fff;
    margin:0;
    padding:0;
    font-family:"微软雅黑";
    .bg-container
      background-image: url("../common/img/loginbg_admin.jpg");
      background-repeat:no-repeat;
      background-position:center;
      height:600px;
      background-size: 100% 100%;
    .login-container
      -webkit-border-radius: 5px;
      border-radius: 5px;
      -moz-border-radius: 5px;
      background-clip: padding-box;
      margin-bottom: 20px;
      background-color: #F9FAFC;
      margin: 110px auto;
      margin-right:13%;
      border: 1px solid #e1e1e1;
      width: 250px;
      padding: 30px 40px 40px 45px;
      .title
        margin: 0px auto 40px auto;
        text-align: center;
        color: #505458;

      .remember
        margin: 0px 0px 35px 0px;
  .linkcolor
    color:#20A0FF;
    font-size:13px;
  .linkcolor:hover
    color:#ff7f0e;
    cursor:pointer;
    transition:color 0.15s ease-in-out;
  #loginbtn
    background-color:#ff7f0e;
    color:#fff;border:none
  #loginbtn:hover
    background-color:#ff8e2b;
    cursor:pointer;
    transition:background-color 0.2s ease-in-out;

</style>
